<template>
  <div class="assign">
    <el-dialog title="项目分配" :visible.sync="assignDialogVisible" width="450px" :append-to-body="true"
      @close="closeAddDialog" class="project-assign">
      <el-form class="form-style" :model="assignInfo" :rules="rules" ref="refAddForm" label-width="80px">
        <el-form-item size="small" label="手机号">
          <el-input disabled v-model="assignInfo.mobile"></el-input>
        </el-form-item>
        <el-form-item size="small" label="用户名">
          <el-input disabled v-model="assignInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item size="small" label="企业" v-if="roleName === 'COMPANY_ADMIN'">
          <div v-if="assignInfo.company">
            <el-input disabled v-model="assignInfo.company.companyName">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item size="small" label="项目" prop="pjtId"
          v-if="roleName === 'COMPANY_ADMIN' || roleName === 'PROJECT_ADMIN'">
          <treeselect v-if="isPjtName" v-model="pjtId" :options="projectList" :normalizer="normalizer"
            :load-options="loadOptions" placeholder="选择项目" noChildrenText="加载中..." noOptionsText="暂无项目"
            noResultsText="无匹配数据" />
          <el-input v-else v-model="assignForm.pjtName" @focus="pjtNameFocus" placeholder="请输入项目名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeAddDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" type="theme" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    reqAssignProject,
    reqProjectIdByUserId
  } from "@api/api-user";
  import {
    reqProjectList,
    reqProjectLevel
  } from "@api/api-project";
  import {
    mapState
  } from "vuex";
  import treeselect from "@riophae/vue-treeselect";
  import "@components/vue-treeselect.less";
  import {
    LOAD_CHILDREN_OPTIONS
  } from "@riophae/vue-treeselect";
  import {
    handleTree
  } from "@utils/trans-tree";
  export default {
    name: "projectAssign",
    props: ["assignInfo"],
    components: {
      treeselect
    },
    data() {
      return {
        normalizer(node) {
          return {
            id: node.id,
            label: node.pjtName,
            children: node.children,
          };
        },
        assignForm: {
          pjtId: null,
          pjtName: "",
        }, //项目id
        pjtId: null, //项目id
        isPjtName: false,
        projectList: [], // 项目列表
        assignDialogVisible: false,
        rules: {
          pjtId: [{
            required: true,
            message: "请选择项目",
            trigger: "blur",
          }, ],
        },
      };
    },
    computed: {
      ...mapState(["roleName", "companyId", "userId"])
    },
    methods: {
      pjtNameFocus() {
        this.isPjtName = true;
      },
      // 根据企业id获取项目列表(companyId)
      async getProjectList() {
        this.projectList = [];
        const res = await reqProjectList({
          roleName: this.roleName,
          userId: this.userId,
          companyId: this.companyId,
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        let {
          rows
        } = res.data;
        this.projectList = handleTree(rows);
        let projectList = this.projectList;
        projectList.forEach((item) => {
          if (item.hasChildren === 1) {
            item.children = null;
          }
        });
        this.projectList = projectList;
      },
      // 树懒加载
      loadOptions({
        action,
        parentNode,
        callback
      }) {
        if (action === LOAD_CHILDREN_OPTIONS) {
          reqProjectLevel({
            pjtId: parentNode.id
          }).then((res) => {
            let arr = [];
            for (let index of res.data.rows) {
              let chiledModeInfo = {};
              chiledModeInfo.id = index.id;
              chiledModeInfo.label = index.pjtName;
              chiledModeInfo.children = null;
              chiledModeInfo.address = index.address;
              chiledModeInfo.area = index.area;
              chiledModeInfo.city = index.city;
              chiledModeInfo.companyId = index.companyId;
              chiledModeInfo.createTime = index.createTime;
              chiledModeInfo.detail = index.detail;
              chiledModeInfo.hasChildren = index.hasChildren;
              chiledModeInfo.level = index.level;
              chiledModeInfo.pjtName = index.pjtName;
              chiledModeInfo.parentId = index.parentId;
              chiledModeInfo.pjtType = index.pjtType;
              chiledModeInfo.province = index.province;
              chiledModeInfo.updateTime = index.updateTime;
              if (index.hasChildren !== 1) {
                delete chiledModeInfo.children; //为末级的时候删掉children，就不会出现末级也有小箭头可以点
              }
              arr.push(chiledModeInfo);
            }
            parentNode.children = arr;
          });
          callback();
        }
      },
      // 获取原有项目id
      async getOriginProjectId() {
        const res = await reqProjectIdByUserId({
          roleName: this.assignInfo.role.name,
          userId: this.assignInfo.id,
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        let {
          pjtList
        } = res.data;
        this.assignForm.pjtId = pjtList.id;
        this.assignForm.pjtName = pjtList.pjtName;
      },
      // 确定按钮
      async addSubmit() {
        if (!this.assignForm.pjtId) {
          this.$modal.notifyWarning("请选择项目");
          return;
        }
        let pjtId = "";
        if (this.pjtId) {
          pjtId = this.pjtId;
        } else {
          pjtId = this.assignForm.pjtId;
        }
        const res = await reqAssignProject({
          userId: this.assignInfo.id,
          pjtId,
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("项目分配成功");
        this.$parent.getUserList(); //更新用户列表
        this.$refs.refAddForm.clearValidate()
        this.assignDialogVisible = false;
        this.pjtId = null;
        this.isPjtName = false;
      },
      // 点击取消和关闭按钮 （ 清除验证  关闭弹窗）
      closeAddDialog() {
        this.projectArr = [];
        this.assignDialogVisible = false;
        this.projectList = [];
        this.projectTotal = 0;
        this.projectPage = 1;
        this.projectLimit = 10;
        this.pjtId = null;
        this.isPjtName = false;
        this.$refs.refAddForm.clearValidate()
      },
      /* 项目分配结束 */
    },
    watch: {
      assignInfo(val) {
        this.getOriginProjectId();
      },
    },
    mounted() {},
  };
</script>

<style lang="less" scoped>
  @import url("../../common.less");
</style>